<template>
<div>
  <el-table
    header-row-class-name="base-table-header-v3"
    :row-class-name="getRowClass"
    class="sparepart-card-table"
    :data="disposeFormListViewTime(data, columns)"
    :show-summary="hasTotalColumn"
    :summary-method="getSummaries"
    border
    @selection-change="handleSelectionChange">
    <template slot="empty">
      <BaseListForNoData
        v-show="!listLoading"
        table-type="smallTable"
        :notice-msg="$t('common.base.tip.noData')"
      ></BaseListForNoData>
    </template>

    <el-table-column type="selection" align="center" width="48"></el-table-column>
    <el-table-column type="index" width="50" :label="$t('common.base.SN')" />

    <!-- start 展开行 -->
    <el-table-column type="expand" width="36" v-if="showExpand">
      <template slot-scope="scope">
        <sparepart-apply-records :data="scope.row.relations" />
      </template>
    </el-table-column>
    <!-- end 展开行 -->

    <el-table-column
      v-for="column in columns"
      :key="column.fieldId"
      :label="column.displayName"
      :prop="column.fieldName"
      show-overflow-tooltip
      :min-width="column.minWidth || '100px'">
      <template slot-scope="scope">
        <!-- start 预计用量 -->
        <template v-if="column.fieldName === 'preNum'">
          <template v-if="!scope.row.editable">
            <span>{{ scope.row[column.fieldName] }}</span>
            <i class="iconfont icon-edit-square" @click="editPreNum(scope.row, scope.$index)" v-if="allowEdit"></i>
          </template>

          <template v-else>
            <input
              type="number"
              v-model="scope.row.preNum"
              @change="handlePreNum(scope.row, scope.$index)"
              @blur="togglePreNumEditable(scope.row, scope.$index)"
            />
          </template>
        </template>
        <!-- end 预计用量 -->

        <!-- start 单价 -->
        <template v-else-if="column.fieldName === 'salePrice'">
          <template v-if="!scope.row.salePriceEditable">
            <span>{{ scope.row[column.fieldName] }}</span>
            <i class="iconfont icon-edit-square" @click="editSalePrice(scope.row, scope.$index)" v-if="editUnitPrice"></i>
          </template>

          <template v-else>
            <input
              type="number"
              v-model="scope.row.salePrice"
              @change="handleSalePrice(scope.row, scope.$index)"
              @blur="toggleSalePriceEditable(scope.row, scope.$index)"
            />
          </template>
        </template>
        <!-- end 单价 -->
        <!-- start 规格 -->
        <template v-else-if="column.fieldName === 'relationStandard'">
          {{ scope.row['standard'] || '' }}
        </template>
        <!-- end 规格 -->

        <!-- start 操作 -->
        <template v-else-if="column.fieldName === 'action'">
          <el-button
            v-if="scope.row.returnBtn && isShowPartBack"
            class="text-danger"
            type="text"
            size="mini"
            @click="partBack(scope.row, scope.$index)"
          >{{$t('task.sparePartsReturn')}}</el-button>
          <el-button
            class="text-danger"
            type="text"
            size="mini"
            @click="deletePart(scope.row, scope.$index)"
          >{{$t('common.base.delete')}}</el-button>
        </template>
        <!-- end 操作 -->

        <template v-else>
          {{ $formatFormField(column, scope.row) }}
        </template>
      </template>
    </el-table-column>
  </el-table>

  <!-- 底部数据量统计 -->
  <div class="table-footer">
    <i18n path="common.base.table.totalCount">
      <span place="count" class="level-padding">{{data.length || 0}}</span>
    </i18n>
  </div>

  <part-back-form 
    ref="partBackForm"
    from="task"
    :back-user='backUser' 
    :repertory="repertory"
    @success="$emit('successReturn')"
  ></part-back-form>
</div>
</template>

<script>
/* api */
import * as TaskApi from '@src/api/TaskApi';
import * as PartApi from '@src/api/SparePart';
/* util */
import MathUtil from '@src/util/math';
/* components */
import SparepartApplyRecords from './SparepartApplyRecords';
import PartBackForm from '@src/modules/partV2/repertory/form/PartBackForm.vue';
/* enum */
import { TaskEventNameMappingEnum } from '@model/enum/EventNameMappingEnum.ts';
/* model */
import { PART_SERVICE_LIST_PRENUM_MAX_LENGTH } from '@src/model/const/Number';
import { PART_SERVICE_LIST_PRENUM_MAX_LENGTH_MESSAGE } from '@src/model/const/Alert';
import { useFormTimezone } from 'pub-bbx-utils'
const { disposeFormListViewTime } = useFormTimezone()

export default {
  name: 'sparepart-card-list',
  props: {
    data: {
      type: Array,
      default: () => ([])
    },
    columns: {
      type: Array,
      default: () => ([])
    },
    partConfig: {
      type: Object,
      default: () => ({})
    },
    allowEdit: {
      type: Boolean,
      default: false
    },
    editUnitPrice: {
      type: Boolean,
      default: false
    },
    listLoading: {
      type: Boolean,
      default: false
    },
    config: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      multipleSelection: [],
      backUser: {},
      repertory: []
    }
  },
  computed: {
    hasTotalColumn() {
      return this.columns.some(c => c.fieldName == 'total')
    },
    // 显示展开行
    showExpand() {
      return this.data.some(item => item.relations.length);
    },
    isShowPartBack() {
      return this.config?.sparePartReturn || false;
    }
  },
  watch: {
    data: {
      immediate: true,
      async handler(){
        // 合并合计列
        await this.$nextTick()
        const tds = document.querySelectorAll('.sparepart-card-table .el-table__footer-wrapper tr>td')
        if (tds.length > 0) {
          tds[1].colSpan = tds.length - 1
          tds.forEach((td, ind) => {
            if (ind != 1) {
              td.display = 'none'
            }
          })
        }
      }
    }
  },
  mounted() {
    this.fetchRepertory();
  },
  methods: {
    disposeFormListViewTime,
    /** 
    * @description 删除备件
    */
    async deletePart(row, index) {
      // 判断已出库的数量
      if (row.useNum > 0) return this.$platform.alert(this.$t('task.tip.deletePartTip1'));
      
      // 判断是否存在待审批的记录
      const warningMsg = row.suspendingFlag ? this.$t('task.tip.deletePartTip2') : this.$t('task.tip.deleteTip');

      let result = await this.$platform.confirm(warningMsg);
      if (!result) return;

      TaskApi.deleteByInventory({inventoryId: row.id})
        .then(res => {
          if (res.success) {
            this.$platform.notification({
              type: 'success',
              title: this.$t('common.base.deleteSuccess')
            })

            this.data.splice(index, 1);

            this.$eventBus.$emit(TaskEventNameMappingEnum.UpdateRecord);
          } else {
            this.$platform.alert(res.message);
          }
        }).catch(err => console.error(err))
    },

    // 点击编辑单价
    editSalePrice(row, index) {
      // 备份单价数据
      row.oldPrice = row.salePrice;
      this.toggleSalePriceEditable(row);
    },

    // 修改单价
    handleSalePrice(item) {
      let value = Number(item.salePrice);
      let count = MathUtil.decimalNumber(value);
      let oldPrice = Number(item.oldPrice ? item.oldPrice : 0);

      if(value < 0){
        this.$platform.alert(this.$t('common.currency.exchangeRateLimit3'));
        item.salePrice = oldPrice;
        return;
      }

      if(count > 2) {
        this.$platform.alert(this.$t('common.currency.exchangeRateLimit4'));
        item.salePrice = oldPrice;
        return;
      }

      const payload = {
        id: item.id,
        preNum: item.preNum,
        salePrice: item.salePrice,
        type: 1
      }
      TaskApi.putTaskInventoryValue(payload)
        .then(res => {
          if (res.success) {
            item.oldPrice = item.salePrice;
            item.total = (item.preNum * item.salePrice).toFixed(2);
          } else {
            this.$platform.alert(res.message);
          }
        }).catch(err => console.error(err))
    },

    // 更新预计用量是否可编辑状态
    toggleSalePriceEditable(row) {
      this.$set(row, 'salePriceEditable', !row.salePriceEditable);
    },

    /**
    * @description 点击编辑预计用量
    */
    editPreNum(row, index) {
      // 备份预计用量数据
      row.backupNum = row.preNum;

      this.togglePreNumEditable(row, index);
    },
    /**
    * @description 修改预计用量
    */
    handlePreNum(item, index) {
      let value = Number(item.preNum);
      let count = this.decimalNumber(value);

      if (value <= 0) {
        this.$platform.alert(this.$t('task.tip.rightNumTip'));
        item.preNum = item.backupNum;
        return;
      }

      if (value > PART_SERVICE_LIST_PRENUM_MAX_LENGTH) {
        this.$platform.alert(`${this.$t('common.base.estimate')}${PART_SERVICE_LIST_PRENUM_MAX_LENGTH_MESSAGE}`);
        item.preNum = item.backupNum;
        return;
      }
      
      if (count != -1 && count == 0) {
        this.$platform.alert(this.$t('task.tip.greaterThanZeroTip1'));
        item.preNum = item.backupNum;
        return;
      }
      
      if (count != -1 && count != 0) {
        this.$platform.alert(this.$t('task.tip.greaterThanZeroTip2', {count}));
        item.preNum = item.backupNum;
        return;
      }

      // 去掉多余0
      item.preNum = item.preNum.replace(/(?:\.0*|(\.\d+?)0+)$/, '$1');

      TaskApi.putTaskInventoryValue({id: item.id, preNum: item.preNum, type: 1})
        .then(res => {
          if (res.success) {
            item.backupNum = item.preNum;
            item.total = (item.preNum * item.salePrice).toFixed(2);
          } else {
            this.$platform.alert(res.message);
          }
        }).catch(err => console.error(err))
    },
    /**
    * @description 预计用量小数位
    */
    decimalNumber(num) {
      let { sparepart2, precision } = this.partConfig;
      let count = MathUtil.decimalNumber(num);

      if(!sparepart2 && count != 0) return 0;
      if(precision >= count) return -1;
      return precision;
    },
    /** 
    * @description 更新预计用量是否可编辑状态
    */
    togglePreNumEditable(row, index) {
      this.$set(row, 'editable', !row.editable);
    },
    // 合计
    getSummaries(param) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (column.property == 'total') {
          const values = data.map(item => Number(item[column.property]))
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return Number(prev) + Number(curr)
              } else {
                return prev
              }
            }, 0)
            sums[1] = `${this.$t('common.base.amountCount')}: ¥${sums[index]}`
            sums[index] = ''
          } else {
            sums[index] = ''
          }
        } else {
          index == 1 ? '' : sums[index] = ''
        }
      });
      return sums;
    },
    handleSelectionChange(value) {
      this.multipleSelection = value;
    },
    getRowClass(item) {
      // 无申请记录时隐藏展开行按钮
      if (!item.row.relations.length) return 'base-table-row-v3 row-expand-cover';

      return 'base-table-row-v3';
    },
    async partBack(stock){
      const row = {
        sparepart: stock
      }
      this.backUser = row;
      this.$refs.partBackForm.open({
        taskCardId: this.$parent?.card?.cardId || '',
        ...row
      })
    },
    fetchRepertory(){
      // 获取仓库类型
      return PartApi.getRepertoryListForTeam().then(result => {
        this.repertory = result || [];
      })
    },
  },
  components: {
    [SparepartApplyRecords.name]: SparepartApplyRecords,
    [PartBackForm.name]: PartBackForm
  }
}
</script>

<style lang="scss">
.sparepart-card-table {
  border-top: 1px solid #ebeef5;

  .el-table__expand-icon  {
    height: 100%;
    top: -2px;
    left: 6px;

    .el-icon {
      font-size: $font-size-base;
      font-weight: bold;
    }
  }

  .row-expand-cover {
    .el-table__expand-icon  {
      display: none;
    }
  }

  .base-table-row-v3 td {
    position: inherit;

    .el-button {
      min-width: auto !important;
      padding: 0;
    }
  }

  .icon-edit-square {
    margin-left: 8px;
    vertical-align: middle;

    &:hover {
      color: $color-primary;
      cursor: pointer;
    }
  }
}
</style>

<style lang="scss" scoped>
::v-deep .el-table__expanded-cell {
  padding: 0 0 0 84px;
  background: $bg-color-l1;

  &:hover {
    background: $bg-color-l1 !important;
  }
}

::v-deep .el-checkbox {
  margin-bottom: 0;
}

input[type="number"] {
  width: 99%;
}
::v-deep .el-table__footer-wrapper tbody td {
  background-color: #F5F7FA !important;
  border: none;
}
</style>
